package com.brossdong.socket.netty.test;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by brossdong on 2018/2/11.
 */
public class Server {

    public static void main(String[] args) throws Exception {

        //1.第一个线程组用于接收Client连接的
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //2.第二个线程组用于实际业务处理的
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        //3.创建一个辅助类,j就是对server端进行一系列配置
        ServerBootstrap b = new ServerBootstrap();
        //将以上线程组加进来
        b.group(bossGroup,workerGroup)
         .channel(NioServerSocketChannel.class)
        //一定要使用childHandler去绑定具体的事件处理器
         .childHandler(new ChannelInitializer<SocketChannel>() {
             @Override
             protected void initChannel(SocketChannel sc) throws Exception {
                sc.pipeline().addLast(new ServerHandler());
             }
         })
         //option()是提供给NioServerSocketChannel用来接收进来的连接
         .option(ChannelOption.SO_BACKLOG, 128)
         //childOption()是提供给由父管道ServerChannel接收到的连接
         //保持连接
         //.childOption(ChannelOption.SO_KEEPALIVE, true);
         .option(ChannelOption.SO_KEEPALIVE, true);

        //绑定指定的端口进行监听
        ChannelFuture f = b.bind(8765).sync();

        f.channel().closeFuture().sync();

        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();

    }
}
